package com.dave.gd.core.common.sequence.handler.impl;

import java.util.HashMap;
import java.util.Map;

import com.dave.gd.common.exception.RtManagerException;
import com.dave.gd.common.util.HttpUtils;
import com.dave.gd.common.util.NumberUtils;
import com.dave.gd.common.util.StringUtils;
import com.dave.gd.core.common.sequence.handler.SeqHandler;
import com.dave.gd.core.services.caller.CallUtils;

/**
 * Created by linzq on 2014/11/15.
 */
public class RemoteSeqHandler implements SeqHandler {
    
    public String getUrl() {
        return CallUtils.getUrl("seqService", "nextId");
    }
    
    @Override
    public Long nextId(String seqName) {
        if (StringUtils.isNullOrEmpty(getUrl())) {
            throw new RtManagerException("未配置Seq服务地址");
        }
        
        Map<String, String> params = new HashMap<String, String>();
        params.put("seq", seqName);
        
        String ret = HttpUtils.getInstance().httpPost(getUrl(), params, false);
        String[] strs = ret.replaceAll("\\{", "").replaceAll("\\}", "").split(",");
        boolean getId = false;
        for (String str : strs) {
            if (str.startsWith("\"id\"")) {
                long id = NumberUtils.nullToLongZero(str.split(":")[1]);
                getId = true;
                return id;
            } else if (str.startsWith("\"err\"")) {
                throw new RuntimeException(StringUtils.strnull(str.split(":")[1]));
            }
        }
        if (!getId) {
            throw new RtManagerException("返回结果错误,返回信息：" + ret);
        }
        return 0L;
    }
}
